package org.biz.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.biz.common.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * ApiAuthenticationEntryPoint
 *
 * @author: xiongwei
 * Date: 2017/5/11
 */
public class ApiAuthenticationEntryPoint implements AuthenticationEntryPoint {
    private Logger logger = LoggerFactory.getLogger(ApiAuthenticationEntryPoint.class);

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
//        logger.error("ApiAuthenticationEntryPoint: url=" + request.getRequestURL(), authException);
        AntPathRequestMatcher matcher = new AntPathRequestMatcher("/sys/**");
        if (matcher.matches(request)) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            Result result = new Result();
            result.setCode(401);
            result.setMessage("UnAuthorized!");
            this.objectMapper.writeValue(response.getWriter(), result);
        } else {
            response.addHeader("WWW-Authenticate", "Basic realm=\"nurse\"");
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
                    authException.getMessage());
        }
    }
}
